<template>
	<view>
		<van-address-edit :area-list="areaList" show-delete show-set-default show-search-result
			:search-result="searchResult" :area-columns-placeholder="['请选择', '请选择', '请选择']" @save="onSave"
			:address-info="addrinfo" @delete="onDelete" />
	</view>
</template>

<script setup>
	import {
		areaList
	} from '@vant/area-data';
	import {
		ref,
		onBeforeMount
	} from 'vue'
	import {
		onShow,
		onLoad
	} from '@dcloudio/uni-app'
	import $http from '../../request/index.js'
	import {
		showSuccessToast,
		showFailToast
	} from 'vant'
	const searchResult = ref([]);

	let addrinfo = ref({})
	let addrId = ref('')

	function onSave(val) { //点击保存，判断是新增还是编辑
		let data = val
		data.addresId = addrId.value
		if (addrId.value) { //如果是编辑
		console.log(data)
			$http.post('/address/edit', data).then(res => {
				console.log(res)
				let {
					code,
					msg
				} = res
				if (!code) {
					showSuccessToast(msg)
				} else {
					showFailToast(msg)
				}
			})
		} else { //如果是新增
			$http.post('/address/add', data).then(res => {
				console.log(res)
				console.log(data)
				let {
					code,
					msg
				} = res
				if (!code) {
					showSuccessToast(msg)
					addrinfo.value = {}
				} else {
					showFailToast(msg)
				}
			})
		}
		// {
		// 	addressDetail: "去玩儿过",
		// 	areaCode: "220523",
		// 	city: "通化市",
		// 	country: "",
		// 	county: "辉南县",
		// 	isDefault: true,
		// 	name: "小朵",
		// 	province: "吉林省",
		// 	tel: "13312345678"
		// }
	}

	function onDelete() { //点击删除，啥也不干，返回地址列表
		uni.navigateBack()
	}
	onLoad((payload) => { //接收传过来的数据
		console.log('接收数据' + payload.id)
		addrId.value = payload.id
		uni.setNavigationBarTitle({
			title: payload.id ? '编辑地址' : '新增地址'
		})
		if (payload.id) {
			// 发请求拿到当前id地址的信息
			$http.get(`/address/${payload.id}`).then(res => {
				console.log(res)
				addrinfo.value = res.data //初始化用户地址信息
			})
		}
	})
</script>

<style>

</style>